<!--
 * 车辆进出管理
 *
-->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item
                ><i
                    class="iconfont icon-car-in-out-menu"
                    style="margin: 5px; font-size: 22px"
                >
                    车辆进出管理</i
                ></el-breadcrumb-item
            >
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-input
                        placeholder="请输入用户名"
                        v-model="queryInfo.person"
                        clearable
                    ></el-input>
                </el-col>
                <el-col :span="4">
                    <el-input
                        v-model="queryInfo.stallArea"
                        placeholder="请输入区域"
                    >
                    </el-input>
                </el-col>
                <el-col :span="10">
                    <el-date-picker
                        v-model="times"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                    >
                    </el-date-picker>
                </el-col>
                <el-col :span="8">
                    <br />
                    <el-button
                        size="small"
                        type="success"
                        icon="iconfont icon-search-menu"
                        style="font-size: 18px"
                        @click="getList"
                    >
                        搜索</el-button
                    >
                </el-col>
            </el-row>

            <el-table v-loading="loading" :data="stallRes" border stripe>
                <el-table-column
                    width="50"
                    label="序号"
                    align="center"
                    type="index"
                ></el-table-column>
                <el-table-column label="用户名" prop="person" align="center">
                </el-table-column>
                <el-table-column
                    label="驶入时间"
                    prop="createTime"
                    align="center"
                >
                    <template slot-scope="scope">
                        {{ dateFormat(scope.row.createTime, 3) }}
                    </template>
                </el-table-column>
                <el-table-column
                    label="驶出时间"
                    prop="overTime"
                    align="center"
                >
                    <template slot-scope="scope">
                        <span v-if="scope.row.overTime">{{
                            dateFormat(scope.row.overTime, 3)
                        }}</span>
                        <el-tag type="success" v-else>未驶出</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="车位区域" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.stall.stallArea }}
                    </template>
                </el-table-column>
                <el-table-column label="车位号" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.stall.stallNum }}
                    </template>
                </el-table-column>
                <el-table-column label="收费" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.overTime">{{ scope.row.money.toFixed(2) }}元</span>
                        <span v-else class="fee-in">
                            <template v-if="scope.row.calculatedFee !== undefined">
                                {{ scope.row.calculatedFee.toFixed(2) }}元
                            </template>
                            <template v-else>
                                <el-tag size="mini" type="info">计算中...</el-tag>
                            </template>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-tooltip
                            class="item"
                            effect="dark"
                            content="驶出扣费"
                            placement="top-start"
                        >
                            <el-button
                                v-if="scope.row.overTime"
                                @click="opare(scope.row)"
                                type="info"
                                circle
                                disabled
                                ><i class="iconfont icon-reduce-button"
                                    style="font-size: 22px"
                                ></i
                            ></el-button>
                            <el-button
                                v-else
                                @click="opare(scope.row)"
                                type="warning"
                                circle
                                ><i class="iconfont icon-reduce-button"
                                    style="font-size: 22px"
                                ></i
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next"
                :total="total"
            >
            </el-pagination>
        </el-card>
    </div>
</template>
<script>
import axios from "axios";
export default {
    data() {
        return {
            total: 0,
            loading: true,
            times: "",
            queryInfo: {
                person: "",
                stallArea: "",
                inTime: "",
                outTime: "",
                pagenum: 1,
                pageSize: 6,
            },
            stallRes: [],
        };
    },
    methods: {
        getList() {
            if (this.times != null && this.times != "") {
                this.queryInfo.inTime = this.times[0];
                this.queryInfo.outTime = this.times[1];
            }
            axios.post("/stall/allList", this.queryInfo).then((res) => {
                this.loading = false;
                this.total = res.data.data.total;
                this.stallRes = res.data.data.records;
                
                // 为每个未结算的停车记录计算费用
                this.stallRes.forEach(item => {
                    if (!item.overTime) {
                        this.calculateFee(item);
                    }
                });
            });
        },
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            this.getList();
        },
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.getList();
        },
        feeChange(stallRes) {
            let startTime = new Date(stallRes.createTime);
            let endTime = new Date();
            let hours = (endTime.getTime() - startTime.getTime()) / 3600000;
            
            // 获取车辆类型
            let carType = stallRes.carType || "小型车"; // 默认为小型车
            
            // 调用获取费率的方法
            return this.getRate(carType, hours);
        },
        // 获取当前车辆类型和时间段的费率
        getRate(carType, hours) {
            // 模拟从服务器获取费率配置
            // 实际项目中应该通过API调用获取
            return new Promise((resolve, reject) => {
                axios.get("/fee-setting/list", {
                    params: {
                        carType: carType
                    }
                }).then(res => {
                    if (res.data && res.data.data && res.data.data.length > 0) {
                        const feeRates = res.data.data;
                        
                        // 获取当前时间
                        const now = new Date();
                        const currentHour = now.getHours();
                        const currentMinutes = now.getMinutes();
                        const currentTimeString = `${String(currentHour).padStart(2, '0')}:${String(currentMinutes).padStart(2, '0')}`;
                        
                        // 查找适用于当前时间的费率
                        let applicableRate = null;
                        
                        for (const rate of feeRates) {
                            // 检查时间段是否适用
                            if (this.isTimeInRange(currentTimeString, rate.startTime, rate.endTime)) {
                                applicableRate = rate;
                                break;
                            }
                        }
                        
                        // 如果没有找到适用的费率，使用默认费率
                        if (!applicableRate && feeRates.length > 0) {
                            applicableRate = feeRates[0];
                        }
                        
                        // 计算费用
                        const fee = applicableRate ? (Math.floor(hours * 10) / 10) * applicableRate.money : 0;
                        resolve(fee);
                    } else {
                        // 使用默认费率
                        const defaultRate = 5; // 默认每小时5元
                        const fee = (Math.floor(hours * 10) / 10) * defaultRate;
                        resolve(fee);
                    }
                }).catch(error => {
                    console.error("获取费率失败:", error);
                    // 使用默认费率
                    const defaultRate = 5; // 默认每小时5元
                    const fee = (Math.floor(hours * 10) / 10) * defaultRate;
                    resolve(fee);
                });
            });
        },
        // 判断当前时间是否在时间范围内
        isTimeInRange(current, start, end) {
            // 处理跨天的情况
            if (start > end) {
                return current >= start || current <= end;
            }
            // 正常时间段
            return current >= start && current <= end;
        },
        // 计算费用并保存到记录中
        calculateFee(stallRes) {
            let startTime = new Date(stallRes.createTime);
            let endTime = new Date();
            let hours = (endTime.getTime() - startTime.getTime()) / 3600000;
            
            // 获取车辆类型
            let carType = stallRes.carType || "小型车"; // 默认为小型车
            
            // 调用获取费率的方法
            this.getRate(carType, hours).then(fee => {
                // 使用Vue.set确保响应性
                this.$set(stallRes, 'calculatedFee', fee);
            });
        },
        async opare(stallRes) {
            // 确保费用已计算
            if (stallRes.calculatedFee === undefined) {
                await this.calculateFee(stallRes);
                // 等待费用计算完成
                await new Promise(resolve => setTimeout(resolve, 500));
            }
            
            const re = await this.$confirm(
                "此操作将" + stallRes.person + "车辆驶出, 是否继续?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).catch((err) => err);
            
            if (re != "confirm") {
                this.$message.info("已取消驶出扣费！");
            } else {
                let oa = {};
                oa.pid = stallRes.pid;
                oa.person = stallRes.person;
                oa.stallId = stallRes.stallId;
                oa.money = stallRes.calculatedFee;
                axios.post("/stall/payMoney", oa).then((res) => {
                    if (res.data.data) {
                        this.$message.success("驶出扣费成功！");
                        this.getList();
                    } else {
                        this.$message.error("驶出扣费失败！");
                    }
                });
            }
        },
        dateFormat(val, timeType) {
            //将字符串或长整型转为时间类型
            let date = new Date(val);
            //默认格式为'年月日 时:分:秒'
            let resultFormat = "Y年M月D日 h:m:s";
            switch (timeType) {
                case 1:
                    resultFormat = "Y年M月D日";
                    break;
                case 2:
                    resultFormat = "Y-M-D";
                    break;
                case 3:
                    resultFormat = "Y-M-D h:m:s";
                    break;
            }
            let result = formatTime(resultFormat);

            // 格式化日期，如月、日、时、分、秒保证为2位数
            function formatNumber(n) {
                n = n.toString();
                return n[1] ? n : "0" + n;
            }
            // 参数number为毫秒时间戳，format为需要转换成的日期格式
            function formatTime(format) {
                let newArr = [];
                let formatArr = ["Y", "M", "D", "h", "m", "s"];
                newArr.push(date.getFullYear());
                newArr.push(formatNumber(date.getMonth() + 1));
                newArr.push(formatNumber(date.getDate()));

                newArr.push(formatNumber(date.getHours()));
                newArr.push(formatNumber(date.getMinutes()));
                newArr.push(formatNumber(date.getSeconds()));

                for (let i in newArr) {
                    format = format.replace(formatArr[i], newArr[i]);
                }
                return format;
            }

            return result;
        },
    },
    mounted() {
        this.getList();
    },
};
</script>
<style scoped>
.fee-in {
    color: red;
}
</style>
